﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using AjaxMasterExtentions;

namespace Dimok.Web.UI {
	public class ProfilerAjax : UserControl, IScriptControl {
		#region Client Properties
		public string WSPath { get; set; }
		#endregion
		ScriptManager sm;

		protected override void OnPreRender(EventArgs e) {
			if (!this.DesignMode) {
				sm = ScriptManager.GetCurrent(Page);
				if (sm == null) throw new HttpException("A ScriptManager control must exist on the current page.");
				sm.RegisterScriptControl(this);
			}
			base.OnPreRender(e);
		}
		protected override void Render(HtmlTextWriter writer) {
			if (!this.DesignMode) sm.RegisterScriptDescriptors(this);
			base.Render(writer);
		}

		public static void SavePagePosition(string pageName, int top, int left, int width, int height) {
			Profiler p = new Profiler(pageName, "");
			var page  = p.Page;
			page.Position.Y = top;
			page.Position.X = left;
			page.Size.Width = width;
			page.Size.Height = height;
			p.Save();
		}
		public static object GetPagePosition(string pageName) {
			var page = new Profiler(pageName, "").Page;
			return new { top = page.Position.Y, left = page.Position.X, width = page.Size.Width, height = page.Size.Height };
		}

		#region IScriptControl Members

		IEnumerable<ScriptDescriptor> IScriptControl.GetScriptDescriptors() {
			Profiler p = this.GetProfiler();
			ScriptBehaviorDescriptor descriptor = new ScriptBehaviorDescriptor("Dimok.ProfilerAjax", "document");
			descriptor.AddProperty("windowTop", p.Page.Position.Y);
			descriptor.AddProperty("windowLeft", p.Page.Position.X);
			descriptor.AddProperty("windowWidth", p.Page.Size.Width);
			descriptor.AddProperty("windowHeight", p.Page.Size.Height);
			descriptor.AddProperty("pageType", p.pageType);
			descriptor.AddProperty("wsPath", (WSPath+"").Default("/manager/webservices/profiler.asmx/") );
			yield return descriptor;
		}

		IEnumerable<ScriptReference> IScriptControl.GetScriptReferences() {
			yield return new ScriptReference("Dimok.Web.UI.JS.Old.Events.js", "Dimok.Web.UI");
			yield return new ScriptReference("Dimok.Web.UI.JS.JQuery.Extentions.js","Dimok.Web.UI");
			yield return new ScriptReference("Dimok.Web.UI.JS.MSAjaxExtentions.js","Dimok.Web.UI");
			yield return new ScriptReference("Dimok.Web.UI.JS.JSON_Lib.js","Dimok.Web.UI");
			yield return new ScriptReference("~/JS/UI/jquery.extentions.js");
			yield return new ScriptReference("/JS/UI/Ajax/Dimok.ProfilerAjax.js");
		}

		#endregion
	}
	
}